var $consumers = $('#consumers');
var $consumerProfile = $('#consumerProfile');
var $documents = $('#documents a');
var $consumerDocuments = $('#consumerDocuments li');
var $admin = $('#userButton, #documentButton');

var $browser = $.browser;

var $dialog = $('div#dialog');
var $alertMessages = $('.alert-message');
var $addButtons = $('.addButton');

var $phoneValidation = $('input.phone');
var $dateInputs = $('input.date');

$.ajaxSetup({ type: "POST" });

var $elements = {};
		$elements['input'] = '<input type="text" id="update-[table]-[id]-[column]" name="update[table][id][column]" class="[class]" />';
 

/*****************************************************
					Global Functions
******************************************************/
(function($){
	$.fn.disableSelection = function() {
	    return this.each(function() {           
	        $(this).attr('unselectable', 'on')
	       		.css({
	            	'-ms-user-select':'none',
	               	'-moz-user-select':'none',
	               	'-webkit-user-select':'none',
	                'user-select':'none'
	         	}).each(function() { 	this.onselectstart = function() { return false; };		});
	 	});
	};
})(jQuery);

(function($) {
	$.fn.textWidth = function() {
		var type = this[0].tagName;
		
		if(type === 'input')
			var textNode = $(this).val();
		else if(type ==='text')
			var textNode = $(this).text();
		else	var textNode = $(this).html();
															alert($('#textWidth').html(textNode).width('auto').innerWidth());
		return $('#textWidth').html(textNode).width();
	};
})(jQuery);

jQuery('#breadcrumbs').jBreadCrumb();

/*****************************************************
					List of Consumers
******************************************************/
if($consumers.length == 1) {
	var gridHeight = function() {
		if($browser.msie)
			return 346;
		else if($browser.mozilla)
			return 330;
		else if($browser.webkit)
			return 345;
		else if($browser.opera)
			return 345;
	}
	
	$('.letters:not(".active"):not(".disabled"):first').addClass('active');

	function fnSetFilterLetter(aoData) {
		aoData.push({ 
	    	"name": "sFilterLetter", 
	    	"value": $('.active').attr('letter') 
	    });	   
 	}
	
	var $consumerGrid = $consumers.dataTable( {		
		"bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": $consumers.attr('list-url') + '?format=json',
		"bLengthChange": false,
		"bFilter": false,
		"sScrollY": $(window).height() - $consumers.offset().top - 100,
		"aaSortingFixed": [[0,'asc']],
		"bPaginate": false,
		"bInfo": false,
		"fnServerParams": fnSetFilterLetter,
		"fnDrawCallback": 
			function() {
				$('.hidden').removeClass("hidden").css({
					'position': 'absolute',
					'top': $('.dataTables_scrollHead th.sorting:last').position().top,
					'left': 0
				});
			},
		"fnServerData": 
			function ( sSource, aoData, fnCallback ) {
				$.ajax({
					"dataType": 'json', 
					"type": "POST", 
					"url": sSource, 
					"data": aoData, 
					"success": fnCallback
				});
			}
	}).rowGrouping({	
		"iGroupingColumnIndex": 0,
		"sGroupBy": "name",
		"sGroupingClass": "ui-widget-content",
		"iHideGroupingColumn": true
	}).disableSelection();
	
	// Init - Filter by Letter
	$(".letters").click( function () {
        // Filter by Letters
        if(!($(this).parent().parent().hasClass("disabled") || $(this).parent().parent().hasClass("active"))) {
        	$('.letters').removeClass("active");
			$(this).addClass("active");

        	$consumerGrid.fnDraw();
        }
    });
	
	// Individual Consumer Hover
	$('body').on('click', 'tr.even, tr.odd',  function() {
		location = $consumers.attr('profile-url') + $(this).attr('id');
	});
}

/*****************************************************
					Consumer Profile
******************************************************/
if($consumerProfile.length > 0) {
	var profileHeight = $(window).height() - $consumerProfile.position().top  - 75;
	var panelHeight =  profileHeight - 110;
	
	$consumerProfile
		.height(profileHeight)
		.tabs({ 
			fx: { opacity: 'toggle' },
			load: function(event, ui) {
				//$(ui.panel).find('a').button({ icons: { primary: 'ui-icon-document' } });
				
        		$(ui.panel)
        			.css({ "height": panelHeight, "overflow":  "auto" })
        			.delegate('a', 'click', function(event) {
            			$(ui.panel).load(this.href);
            			event.preventDefault();
        			});
        	}
		});

	$('.ui-tabs-nav li').each(function(intRow) {
		var tabStyle = 'ui-tabs-' + (intRow + 1);
		$(this).removeClass('ui-state-default').addClass(tabStyle).disableSelection();
		
		if(intRow == 5) $(this).css({ 'borderBottom': '1px solid #000000 !important' });
	});	
}

/*****************************************************
		Admin - jQuery Dialog UI
******************************************************/
if($admin.length == 2) {	
	$admin
	.disableSelection()
	.on( "click", function() {
			var $adminType = $(this).attr('admin-type');
			var $dialogTitle = ($adminType == "User") ? "<em>User Settings</em>" : "<em>Document Settings</em>";
			
			$dialog.html("").load('./adminSettings/' + $adminType).dialog({
				title: $dialogTitle,
				height: $(window).height() * .75,
				width: '75%',
				modal: true,
				resizable: false,
				draggable: false,
				buttons: {
					"Save": function() {
						if($adminType == "User") {
							if($('#Users').validationEngine("validate")) {
								$(this).dialog("close");

								$('tr.currentUsers div.user-edit, tr.currentUsers div.userType-edit')
									.filter(function(index) {
										return $(this).attr('style') == "display: none;";
									}).remove();

								submitUserUpdates();	
							}
						} else {
							if($('#Documents').validationEngine("validate")) {
								$(this).dialog("close");
								submitDocumentUpdates();
							}
						}
					},										
					"Close": function() {
						$('form').validationEngine("detach");
						$(this).dialog("close");
					}
				}
			});
	});
	
	//--> Admin - Saves User Object
	function submitUserUpdates() {		
		var $form  = $('#Users').serialize();
		$.ajax({
			url:	$('#Users').attr('action'),
			data: $form, 
			complete: function() {
				$('#userButton').click();
			}
		});
	}
	
		//--> Admin - Saves Document Object
	function submitDocumentUpdates() {		
		var $form  = $('#Documents').serialize();
		$.ajax({
			url:	$('#Documents').attr('action'),
			data: $form, 
			complete: function() {
				$('#documentButton').click();
			}
		});
	}
}

/*****************************************************
					Tooltip Bindings
******************************************************/
$('a.editButton').tipsy({
	gravity: 'w',
	fade: true,
	live: true
});

$('a.addButton, a.deleteButton').tipsy({
	gravity: 'w',
	fade: true,
	live: true
})

$('input').tipsy({
	gravity: 's',
	fade: true,
	live: true	
});
/*****************************************************
					Form Validations
******************************************************/
// Numeric Validation - Disable Keydown/Keypress
$('body').on("keydown", '.numeric', function(event) {
	var isLetter = event.keyCode > 65 && event.keyCode < 90;
	var isChar = event.keyCode > 188 && event.keyCode < 222;

	 if($browser.msie || $browser.webkit)
		isChar = isChar && event.keyCode > 186 && event.keyCode < 187 && event.keyCode == 189;
	else if($browser.mozilla)
		isChar = isChar && event.keyCode == 109 && event.keyCode == 107 && event.keyCode == 59;
	else if($browser.opera)
		isChar = isChar && event.keyCode == 59 & event.keyCode == 61 && event.keyCode == 109;

	if(isLetter || isChar)
		return false;
	else return true;
}).on("keyup", '.numeric', function(event) {
	if($(this).hasClass('phone-3'))
		var maxLength = 3;
	else if($(this).hasClass('phone-4'))
		var maxLength = 4;

if($(this).val().length == maxLength)
		$(this).nextAll('.numeric:first').focus().select();	
});

function submitForm() {
	if($('form').validationEngine("validate")) {
		alert('sweet');
	} else alert('no way jose!');
}
/*****************************************************
				jQuery Date Picker UI
******************************************************/
$dateInputs.datepicker({
	dateFormat: 'MM dd, yy'
});

/*****************************************************
			Auto-Resize Events
******************************************************/